package cn.pegasus.teamwork.appinterface.controller.pay;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jdom.JDOMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.exceptions.ClientException;

import cn.pegasus.teamwork.appinterface.base.BaseController;
import cn.pegasus.teamwork.appinterface.util.XMLUtil;
import cn.pegasus.teamwork.pegasus.entity.BussOrderNotify;
import cn.pegasus.teamwork.pegasus.service.BussOrderNotifyService;
import cn.pegasus.teamwork.pegasus.service.BussUserConsumorderService;
import cn.pegasus.teamwork.pegasus.service.BussUserOrderService;
import cn.pegasus.teamwork.pegasus.service.BussWasherDepositService;
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping(value = "/notify/*")
public class WeChatOrderController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(WeChatOrderController.class);

	/**
	 * 用户消费订单表service
	 */
	@Autowired
	private BussUserConsumorderService consumorderService;
	
	@Autowired
	private BussOrderNotifyService orderNotifyService;

	/**
	 * service
	 */
	@Autowired
	private BussUserOrderService bussUserOrderService;
	
	@Autowired
	private BussWasherDepositService bussWasherDepositService;

	/**
	 * 申请退款
	 */
	@RequestMapping(value = "/rfnotify")
	public String refundNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml");
		InputStream inStream = null;
		try {
			inStream = request.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		try {
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			outSteam.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 交易状态
		 String result = "";// 获取微信调用我们notify_url的返回信息
		 try {
		 result = new String(outSteam.toByteArray(), "utf-8");
		 LOGGER.info("get to weixin for  result  data ---------------： " + result);
		 } catch (UnsupportedEncodingException e) {
		 e.printStackTrace();
		 }
		String resultMap = "";
		
		Map<String, Object> param =  XMLUtil.doXMLParse(result);
		LOGGER.info("get to weixin for data ： " + param);

		String trade_status = param.get("result_code").toString();
		String return_code = param.get("return_code").toString();

		if (trade_status.equals("SUCCESS") && return_code.equals("SUCCESS")) {
			String orderNO = param.get("out_trade_no").toString();
			String transaction_id = param.get("transaction_id").toString();
			String total_fee = param.get("total_fee").toString();
			synchronized (this) {
				// 进行业务处理
				if (!StringUtils.isEmpty(orderNO)) {
					LOGGER.info("begin to services proess " + orderNO);	
					if(isExiteDate(orderNO,2)){
						if (bussUserOrderService.modifyRefundOrder(transaction_id, total_fee, orderNO)) {
							LOGGER.info("end to services proess ! success" + "-----rechargeNotify" );
							addOrderNotify(orderNO,2,transaction_id);
							resultMap = XMLUtil.setXML("SUCCESS", "OK");
						} else {
							resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
						}
					}else {
						resultMap = XMLUtil.setXML("SUCCESS", "该订单已经处理完毕，无需在处理");
					}			
				} else {
					resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
				}
			}
		}
		return resultMap;
	}

	/**
	 * 异步返回-用户充值
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws JDOMException 
	 */
	@RequestMapping(value = "/renotify")
	public String rechargeNotify(HttpServletRequest request, HttpServletResponse response)
			throws IOException, JDOMException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml");
		InputStream inStream = null;
		try {
			inStream = request.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		try {
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			outSteam.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 交易状态
		 String result = "";// 获取微信调用我们notify_url的返回信息
		 try {
		 result = new String(outSteam.toByteArray(), "utf-8");
		 LOGGER.info("get to weixin for  result  data ---------------： " + result);
		 } catch (UnsupportedEncodingException e) {
		 e.printStackTrace();
		 }
		String resultMap = "";
		
		Map<String, Object> param =  XMLUtil.doXMLParse(result);
		LOGGER.info("get to weixin for data ： " + param);

		String trade_status = param.get("result_code").toString();
		String return_code = param.get("return_code").toString();

		if (trade_status.equals("SUCCESS") && return_code.equals("SUCCESS")) {
			String orderNO = param.get("out_trade_no").toString();
			String transaction_id = param.get("transaction_id").toString();
			String total_fee = param.get("total_fee").toString();
			synchronized (this) {
				// 进行业务处理
				if (!StringUtils.isEmpty(orderNO)) {
					LOGGER.info("begin to services proess " + orderNO);	
					if(isExiteDate(orderNO,1)){
						if (consumorderService.modifyRechargeOrder(transaction_id, total_fee, orderNO)) {
							LOGGER.info("end to services proess ! success" + "-----rechargeNotify" );
							addOrderNotify(orderNO,1,transaction_id);
							resultMap = XMLUtil.setXML("SUCCESS", "OK");
						} else {
							resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
						}
					}else {
						resultMap = XMLUtil.setXML("SUCCESS", "该订单已经处理完毕，无需在处理");
					}					
					
				} else {
					resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
				}
			}
		}
		return resultMap;
	}

	/**
	 * 异步返回 用户支付已经创建的订单 获取到订单信息，更新订单支付状态，变更用户资金明细，分配订单给洗车工
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws JDOMException 
	 * @throws ClientException 
	 */
	@ResponseBody
	@RequestMapping(value = "/punotify")
	public String purchaseNotify(HttpServletRequest request, HttpServletResponse response)
			throws IOException, JDOMException, ClientException {
		LOGGER.info("已经开始了 购买洗车订单的回调业务===666666666===");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml");
		InputStream inStream = null;
		try {
			inStream = request.getInputStream();
			LOGGER.info("获取到的流数据为 -----： " + inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		try {
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			outSteam.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// 交易状态
		String result = "";// 获取微信调用我们notify_url的返回信息
		try {
			result = new String(outSteam.toByteArray(), "utf-8");
			LOGGER.info("获取到的字符串数据为 ----： " + result);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String resultMap = "";
		// XMLUtil.parseXmlToMap(result);
		Map<String, Object> param =  XMLUtil.doXMLParse(result);
		LOGGER.info("获取到的参数为 ： " + param);

		String trade_status = param.get("result_code").toString();
		String return_code = param.get("return_code").toString();

		if (trade_status.equals("SUCCESS") && return_code.equals("SUCCESS")) {
			String orderNO = param.get("out_trade_no").toString();
			String transaction_id = param.get("transaction_id").toString();
			String total_fee = param.get("total_fee").toString();
			synchronized (this) {
				// 进行业务处理
				LOGGER.info("处理业务开始---------- ： ");
				
				if (!StringUtils.isEmpty(orderNO)) {
					LOGGER.info("begin to services proess " + orderNO);	
					if(isExiteDate(orderNO,3)){
						if (bussUserOrderService.modifyPurchaseOrder(transaction_id, total_fee, orderNO)) {
							LOGGER.info("end to services proess ! success" + "-----rechargeNotify" );
							addOrderNotify(orderNO,3,transaction_id);
							resultMap = XMLUtil.setXML("SUCCESS", "OK");
						} else {
							resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
						}
					}else {
						resultMap = XMLUtil.setXML("SUCCESS", "该订单已经处理完毕，无需在处理");
					}		
				} else {
					resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
				}
				LOGGER.info("处理业务结束---------- ： ");
			}
		}
		return resultMap;
	}
	
	/**
	 * 异步返回 用户支付打赏的订单 获取到订单信息，更新订单支付状态，变更用户资金明细
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws JDOMException 
	 */
	@ResponseBody
	@RequestMapping(value = "/rdnotify")
	public String rrewardNotify(HttpServletRequest request, HttpServletResponse response)
			throws IOException, JDOMException {
		LOGGER.info("已经开始了 购买洗车订单的回调业务===666666666===");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml");
		InputStream inStream = null;
		try {
			inStream = request.getInputStream();
			LOGGER.info("获取到的流数据为 -----： " + inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		try {
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			outSteam.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 交易状态
		String result = "";// 获取微信调用我们notify_url的返回信息
		try {
			result = new String(outSteam.toByteArray(), "utf-8");
			LOGGER.info("获取到的字符串数据为 ----： " + result);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String resultMap = "";
		// XMLUtil.parseXmlToMap(result);
		Map<String, Object> param =  XMLUtil.doXMLParse(result);
		LOGGER.info("获取到的参数为 ： " + param);

		String trade_status = param.get("result_code").toString();
		String return_code = param.get("return_code").toString();

		if (trade_status.equals("SUCCESS") && return_code.equals("SUCCESS")) {
			String orderNO = param.get("out_trade_no").toString();
			String transaction_id = param.get("transaction_id").toString();
			String total_fee = param.get("total_fee").toString();
			synchronized (this) {
				// 进行业务处理
				LOGGER.info("处理业务开始---------- ： ");
				if (!StringUtils.isEmpty(orderNO)) {
					LOGGER.info("begin to services proess " + orderNO);	
					if(isExiteDate(orderNO,4)){
						if (bussUserOrderService.modifyRrewardOrder(transaction_id, total_fee, orderNO)) {
							LOGGER.info("end to services proess ! success" + "-----rrewardNotify" );
							addOrderNotify(orderNO,4,transaction_id);
							resultMap = XMLUtil.setXML("SUCCESS", "OK");
						} else {
							resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
						}
					}else {
						resultMap = XMLUtil.setXML("SUCCESS", "该订单已经处理完毕，无需在处理");
					}		
				} else {
					resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
				}
				LOGGER.info("处理业务结束---------- ： ");
			}
		}
		return resultMap;
	}

	/**
	 * 洗车工交付押金时候的回调
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws JDOMException 
	 */
	@ResponseBody
	@RequestMapping(value = "/dtnotify")
	public String depositNotify(HttpServletRequest request, HttpServletResponse response)
			throws IOException, JDOMException {
		LOGGER.info("已经开始了 购买洗车订单的回调业务===666666666===");

		InputStream inStream = null;
		try {
			inStream = request.getInputStream();
			LOGGER.info("获取到的流数据为 -----： " + inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		try {
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			outSteam.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 交易状态
		String result = "";// 获取微信调用我们notify_url的返回信息
		try {
			result = new String(outSteam.toByteArray(), "utf-8");
			LOGGER.info("获取到的字符串数据为 ----： " + result);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String resultMap = "";
		// XMLUtil.parseXmlToMap(result);
		Map<String, Object> param =  XMLUtil.doXMLParse(result);
		LOGGER.info("获取到的参数为 ： " + param);

		String trade_status = param.get("result_code").toString();
		String return_code = param.get("return_code").toString();

		if (trade_status.equals("SUCCESS") && return_code.equals("SUCCESS")) {
			String orderNO = param.get("out_trade_no").toString();
			String transaction_id = param.get("transaction_id").toString();
//			String total_fee = param.get("total_fee").toString();
			synchronized (this) {
				// 进行业务处理
				LOGGER.info("处理业务开始---------- ： ");
				if (!StringUtils.isEmpty(orderNO)) {
					LOGGER.info("begin to services proess " + orderNO);	
					if (bussWasherDepositService.modifyWasherDepositOrder(transaction_id, orderNO)) {
						LOGGER.info("end to services proess ! success" + "----- depositNotify" );	
						resultMap = XMLUtil.setXML("SUCCESS", "OK");
					} else {
						resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
					}
				} else {
					resultMap = XMLUtil.setXML("FAIL", "数据格式化失败");
				}
				LOGGER.info("处理业务结束---------- ： ");
			}
		}
		return resultMap;
	}

	/**
	 * 判断回调结果是否已经被处理
	 * @param orderNo
	 * @param orderType
	 * @return
	 */
	public boolean isExiteDate(String orderNo,int orderType){
		Map<String, Object> param =  new HashMap<String, Object>();
		param.put("orderNo", orderNo);
		param.put("orderType", orderType);
		BussOrderNotify bussOrderNotify = orderNotifyService.detail(param);
		if(bussOrderNotify != null){
			LOGGER.info("处理业务结束---------- ： " + bussOrderNotify.getId());
			return false;
		}else {
			LOGGER.info("没有查出相关的记录。。。。。。。。。。。。。" );
			return true;
		}
	}
	
	/**
	 * 对已经调用成功的，进行添加
	 * @param orderNo
	 * @param orderType
	 * @return
	 */
	public void addOrderNotify(String orderNo,int orderType,String transactionId){
		try {
			BussOrderNotify bussOrderNotify = new BussOrderNotify();
			bussOrderNotify.setOrderNo(orderNo);
			bussOrderNotify.setTransactionId(transactionId);
			bussOrderNotify.setOrderType(orderType);
			bussOrderNotify.setOrderStatus(2);		
			orderNotifyService.add(bussOrderNotify);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}